﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KamLib;


namespace Ext.Net.UIS
{

    public class Grid : GridPanel, ITermBox
    {

        public string Name { get; set; }
        public new Context Context { get; set; }
        public Term Term { get; set; }
        public TermNode ParentTermNode { get; set; }
        public TermNode TermNode { get; set; }

        public bool ControlsCreated { get; set; }

        public void CreateControls(UisCreateControlArgs e)
        {
            this.UisGetTermNode();
            if (TermNode == null) return;

            TermNode.ApplyToGrid(this);
            this.UisAddTermNodeConfigItem();

            AddColumns();
        }


        private void AddColumns()
        {
            if (Term == null) return;

            if (!Term.IsAnonymous)
                AddColumn(Term, ColumnModel.Columns);
            else
            {
                foreach (var item in Term.Items)
                {
                    AddColumn(item, ColumnModel.Columns);
                }
            }
        }

        private void AddColumn(Term term, ItemsCollection<ColumnBase> columns)
        {

            if (term.IsLabel()) return;

            if (term.IsAnonymous)
            {
                foreach (var item in term.Items)
                {
                    AddColumn(item, columns);
                }
            }
            else
            {
                var col = new Column
                {
                    Text = term.Title,
                    DataIndex = term.Items.Count == 0 ? term.Name : null,
                    Width = term.Width,
                };
                columns.Add(col);

                if (term.Items.Count == 0)
                {
                    TermNode.Using(term);
                }
                else
                {
                    foreach (var item in term.Items)
                    {
                        AddColumn(item, col.Columns);
                    }
                }
            }

        }


    }

}
